<?php

//include("ext/mime.php");
$sanitize_all_escapes = true;

//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;

$ignoreAuth = true;
require_once('../../../interface/globals.php');
require_once("$srcdir/patient.inc");

$establecimiento = '';
$authUserID = $_SESSION["authId"];
$comentarios = (isset($_REQUEST['comentarios']) ? $_REQUEST['comentarios'] : '');
$clean = (isset($_REQUEST['clean']) ? 1 : 0);
$espirometro = (isset($_REQUEST['espirometro']) ? 1 : 0);


$result2 = sqlStatement("select facility_id from users_facility where table_id = '$authUserID'");
if ($row2 = sqlFetchArray($result2)) {
    $_SESSION['pc_facility'] = $row2['facility_id'];
    $provider_facility_id = $row2['facility_id'];
}

switch ($_SESSION['pc_facility']) {
    case 19: //cartagena1
        $establecimiento = "cartagena1";
        break;
    case 20: //cartagena2
        $establecimiento = "cartagena2";
        break;
    case 21: //cartagena3
        $establecimiento = "cartagena3";
        break;
    case 22: //cartagena4
        $establecimiento = "cartagena4";
        break;
    case 23: //ESE Hospital Local Ana María Rodríguez
        $establecimiento = "arenal";
        break;
    case 24: //ESE Hospital Local San José de Achí
        $establecimiento = "achi";
        break;
    case 25: //ESE Hospital José Reducindo López P.
        $establecimiento = "barranco";
        break;
    case 26: //ESE Hospital Universitario del Caribe - Sede Mompox
        $establecimiento = "mompox";
        break;
    case 27: //ESE Hospital Local La Candelaria
        $establecimiento = "rioviejo";
        break;
    case 28: //ESE Hospital San Antonio de Padua
        $establecimiento = "simiti";
        break;
}

$categoria = '';
$catid = 0;
$tipoexamen = $_REQUEST['tipoexamen'];

switch ($tipoexamen) {
    case 1: //Auscultaciones Cardiacas
        $categoria = "estetoscopio";
        $catid = 22;
        break;
    case 2: //Auscultaciones Respiratorias
        $categoria = "estetoscopio";
        $catid = 23;
        break;
    case 3: //Dermatologías
        $categoria = "camdermatologica";
        $catid = 19;
        break;
    case 4: //Electrocardiogramas
        $categoria = "ecg";
        $catid = 21;
        break;
    case 5: //Espirometrías
        $categoria = "espirometro";
        $catid = 20;
        break;
    case 6: //Otoscopias
        $categoria = "camdermatologica";
        $catid = 24;
        break;
}

$sourcepath = $GLOBALS['fileroot'] . "/sites/default/establecimientos/" . $establecimiento . "/" . $categoria; //PATH ORIGEN

$savedpath = $GLOBALS['fileroot'] . "/sites/default/documents/" . $pid; //PATH DESTINO

if (!is_dir($savedpath)) {
    mkdir($savedpath, 0777, true);
    chmod($savedpath, 0777);
}

$srvpath = $_SERVER['DOCUMENT_ROOT'] . "home/dcmhl7/mysac/espirometro/incoming";

if (!is_dir($srvpath)) {
        mkdir($srvpath, 0777, true);
        chmod($srvpath, 0777);
}

define("_SOURCE", $sourcepath . "/");
define("_DESTINATION", $savedpath . "/");
define("_ESPIROMETRO_PATIENTS_SRC", $srvpath . "/");

// Identify directories
$source = _SOURCE;
$savedpath = _DESTINATION;
$espirometroSrv = _ESPIROMETRO_PATIENTS_SRC;

if ($espirometro == 1) {   
    $query = "SELECT count(d.id) as c
              FROM documents AS d, categories_to_documents AS cd, categories AS c 
              WHERE d.foreign_id = $pid AND cd.document_id = d.id AND c.id = cd.category_id AND c.id=20";
    
    $dres = sqlStatement($query);
    $drow = sqlFetchArray($dres);
    $numRes = $drow['c'];
    
    if($numRes>0){
        
        $query = $query = " SELECT * 
                    FROM patient_data 
                    LEFT JOIN municipios m on patient_data.municipio=m.id 
                    WHERE patient_data.id = " . $pid;
        $result = sqlStatement($query);
        $patient = sqlFetchArray($result);
        
        $myfile = fopen($espirometroSrv."Patient.srv", "w") or die("Unable to open file!");
        $txt = "[Identification]\n";
        fwrite($myfile, $txt);
        $txt = "ID=".$patient['pubpid']."\n";
        fwrite($myfile, $txt);
        $txt = "LastName=".$patient['lname']." ".$patient['lname2']."\n";
        fwrite($myfile, $txt);
        $txt = "FirstName=".$patient['fname']."\n";
        fwrite($myfile, $txt);
        $date = new DateTime($patient['DOB']);
        $txt = "BirthDate=".$date->format('d/m/Y')."\n";
        fwrite($myfile, $txt);
        $txt = "Gender=".($patient['sex']=='Female'?1:0)."\n";
        fwrite($myfile, $txt);
        $txt = "EthnicGroup=10\n";
        fwrite($myfile, $txt);
        //TODO
        $txt = "Height=178\n";
        fwrite($myfile, $txt);
        $txt = "Weight=73\n";
        fwrite($myfile, $txt);
        $txt = "Smoke=0\n";
        fwrite($myfile, $txt);
        $txt = "Address=".$patient['street']."\n";
        fwrite($myfile, $txt);
        /*$txt = "PostalCode=10311\n";
        fwrite($myfile, $txt);*/
        $txt = "City=".$patient['nombre']."\n";
        fwrite($myfile, $txt);
        $txt = "Job=".$patient['ocupaciones2']."\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }    
} else {
    $files = scandir(_SOURCE);

    //print_r/($files); die;
    //
    // Cycle through all source files
    foreach ($files as $file) {
        if (in_array($file, array(".", "..", ".svn")))
            continue;

        $fsize = filesize($source . $file);
        $timeFile = filemtime($source . $file);
        $filetype = mimetype($source . $file);
        $currenthash = sha1_file($source . $file);
        $path_parts = pathinfo($file);
        $t = time();
        $basename = $path_parts['basename'];
        $name = $t . "-" . $basename;

        if ($clean != 1) {
            rename($source . $basename, $source . $name);

            $docdate = date("Y-m-d", $timeFile);

            $path = _DESTINATION . $name;

            //echo "resultado==>". $pid . "\n" . $fsize . "\n" . $path . "<br/>" . $docdate . "<br/>" . $categoria . "<br/>" . $catid . "<br/>";
            guardar_documento($pid, $fsize, $path, $docdate, $catid, $filetype, $currenthash, $pid, $tipoexamen, $comentarios);

            // If we copied this successfully, mark it for deletion
            if (copy($source . $name, $savedpath . $name)) {
                $delete[] = $source . $name;
            }
        } else {
            unlink($source . $basename);
        }
    }
    // Delete all successfully-copied files
    foreach ($delete as $file) {
        unlink($file);
    }
}

echo "true";
//print_r($_SESSION);

function guardar_documento($patient_id, $fsize, $target, $docdate, $catid, $filetype, $currenthash, $pid, $tipoexamen, $comentarios) {
    $encounter = $_SESSION['encounter'];

    //TO DOCUMENTS
    $query = "INSERT INTO documents ( " .
            "type, size, date, url, mimetype, foreign_id, docdate, hash, source_entry, fromEX,encounter" .
            " ) VALUES ( " .
            "'file_url', '$fsize', NOW(), 'file://$target', '" .
            $filetype . "', $patient_id, '$docdate', '$currenthash', '0', '1','$encounter' " . ")";

    $newid = sqlInsert($query);

    $query = "INSERT INTO categories_to_documents ( " .
            "category_id, document_id" .
            " ) VALUES ( " .
            "'$catid', '$newid' " .
            ")";
    sqlStatement($query);

    //TO FORM_EXAMENES
    if (!$user)
        $user = $_SESSION['authUser'];
    if (!$group)
        $group = $_SESSION['authProvider'];
    $userauthorized = $_SESSION['userauthorized'];

    $sql = "insert into form_examenes (date, activity, pid, " .
            "tipoexamen, estado, comentarios,documentid) values (";
    $sql .= "NOW(),'1','$pid', '$tipoexamen', '1', '$comentarios', '$newid')";

    //Insert into bitacora
    off_sync($sql);

    $formExid = sqlInsert($sql);

    //TO FORMS
    $sql2 = "insert into forms (date, encounter, form_name, form_id, pid, " .
            "user, groupname, authorized, formdir) values (";
    $sql2 .= "NOW(), '$encounter', 'Examen', '$formExid', '$pid', '$user',          " .
            "'$group', '$userauthorized', 'examenes')";

    //Insert into bitacora
    off_sync($sql2);

    sqlInsert($sql2);
}

function mimetype($filepath) {
    // Check only existing files
    if (!file_exists($filepath) || !is_readable($filepath))
        return "NA";

    // Trying finfo
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME);
        $mimeType = finfo_file($finfo, $filepath);
        finfo_close($finfo);
        // Mimetype can come in text/plain; charset=us-ascii form
        if (strpos($mimeType, ';'))
            list($mimeType, ) = explode(';', $mimeType);
        return $mimeType;
    }

    // Trying mime_content_type
    if (function_exists('mime_content_type')) {
        return mime_content_type($filepath);
    }

    // Trying exec
    if (function_exists('exec')) {
        $mimeType = exec("file -i -b $filepath");
        if (!empty($mimeType))
            return $mimeType;
    }

    // Trying to get mimetype from images
    $imageData = @getimagesize($filepath);
    if (!empty($imageData['mime'])) {
        return $imageData['mime'];
    }

    $mimetypes = array(
        'gif' => 'image/gif',
        'png' => 'image/png',
        'jpg' => 'image/jpg',
        'css' => 'text/css',
        'js' => 'text/javascript',
        'pdf' => 'application/pdf',
    );
    $path_parts = pathinfo($filepath);
    if (array_key_exists($path_parts['extension'], $mimetypes)) {
        return $mimetypes[$path_parts['extension']];
    }

    return "application/octet-stream";
}

?>